<?php
namespace App\Controller;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use App\Job\RugbyArticleJob;
use App\Job\RugbyReviewJob;
use Hyperf\Logger\LoggerFactory;
use App\Service\RugbyArticleService;
use App\Service\RugbyReviewService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;

/**
 * @Controller(prefix="api/rugby")
 */
class RugbyController
{
    protected $response;
    protected $queue;
    protected $loggerFactory;

    public function __construct(
        HttpResponse $response,
        DriverFactory $driverFactory,
        LoggerFactory $loggerFactory
    ) {
        $this->response = $response;
        $this->queue = $driverFactory->get('default');
        $this->loggerFactory = $loggerFactory;
    }

    /**
     * 商品文章写入
     * @PostMapping(path="irugby_insert_product_blog")
     */
    public function irugbyInsertProductBlog(RequestInterface $request): ResponseInterface
    {
        try {
            $conn_i = Db::connection('irugbystore');

            $json = $request->getBody()->getContents();
            $getData = json_decode($json, true);

            $post_title             = trim($getData['post_title']);
            $description            = trim($getData['description']);
            $content                = $getData['content'];
            $tags                   = trim($getData['tags']);
            $meta_tag_title         = trim($getData['meta_tag_title']);
            $meta_tag_description   = trim($getData['meta_tag_description']);
            $meta_keywords          = trim($getData['meta_keywords']);
            $language_id            = (int)$getData['language_id'];
            $product_id             = (int)$getData['product_id'];
            $post_url               = ltrim(trim($getData['post_url']), '/');
            $post_url               = 'blog/'.$post_url;
            $product_image          = trim($getData['product_image']);
            $post_scene             = trim($getData['post_scene']);
            $post_keywords          = trim($getData['post_keywords']) ?? '';

            $conn_i->beginTransaction();

            $author_id = rand(1,3);

            //oc_blog_article
            $oc_blog_article_image = strtok($product_image, '?');
            $oc_blog_article_image = parse_url($oc_blog_article_image, PHP_URL_PATH);
            $oc_blog_article_image = ltrim($oc_blog_article_image, '/');

            $local_blog_count = $conn_i->table('oc_blog_count')
                ->select('blog_count_id','blog_id')
                ->where('product_id', $product_id)
                ->where('language_id', $language_id)
                ->where('scane', $post_scene)
                ->first();
            if($local_blog_count){
                return $this->response->json([
                    'code' => 400,
                    'msg' => '该场景文章已经存在'
                ]);
            }

            $fan_language_id = ($language_id == 1) ? 2 : 1;
            $fan_blog_count = $conn_i->table('oc_blog_count')
                ->select('blog_count_id','blog_id')
                ->where('product_id', $product_id)
                ->where('language_id', $fan_language_id)
                ->where('scane', $post_scene)
                ->first();

            if ($fan_blog_count) {
                $blog_article_id = (int)$fan_blog_count->blog_id;
            }else{
                //oc_blog_article
                $blog_article_id = $conn_i->table('oc_blog_article')->insertGetId([
                    'author_id' => $author_id,
                    'article_list_gallery_display' => 'SLIDER',
                    'sort_order' => 1,
                    'image' => $oc_blog_article_image,
                    'status' => 1,
                    'status_comments' => 1,
                    'date_added' => date('Y-m-d H:i:s'),
                    'date_published' => date('Y-m-d H:i:s', strtotime("+$author_id minutes")),
                    'date_updated' => date('Y-m-d H:i:s')
                ]);

                //oc_blog_count
                $conn_i->table('oc_blog_count')->insert([
                    'product_id' => $product_id,
                    'language_id' => $language_id,
                    'blog_id' => $blog_article_id,
                    'keywords' => $post_keywords,
                    'scane' => $post_scene,
                    'json_data' => json_encode([]),
                ]);
                //oc_blog_article_to_category
                $conn_i->table('oc_blog_article_to_category')->insert([
                    'article_id' => $blog_article_id,
                    'category_id' => 1
                ]);

                //oc_blog_article_to_store
                $conn_i->table('oc_blog_article_to_store')->insert([
                    'article_id' => $blog_article_id,
                    'store_id' => 0
                ]);

                //oc_blog_product_related
                $conn_i->table('oc_blog_product_related')->insert([
                    'article_id' => $blog_article_id,
                    'related_id' => $product_id
                ]);
            }

            //oc_blog_article_description
            $conn_i->table('oc_blog_article_description')->insert([
                [
                    'article_id' => $blog_article_id,
                    'language_id' => $language_id,
                    'title' => $post_title,
                    'description' => $description,
                    'content' => $content,
                    'tags' => $tags,
                    'meta_title' => $meta_tag_title,
                    'meta_description' => $meta_tag_description,
                    'meta_keyword' => $meta_keywords
                ]
            ]);

            $conn_i->table('oc_url_absolute')->insert([
                [
                    'query' => 'blog/article&article_id=' . $blog_article_id,
                    'redirect' => $post_url.'-'.$blog_article_id,
                    'language_id' => $language_id
                ],
                [
                    'query' => 'product/blog&blog_id=' . $blog_article_id,
                    'redirect' => $post_url.'-'.$blog_article_id,
                    'language_id' => $language_id
                ]
            ]);

            //oc_blog_count
            $oc_blog_count_count = $conn_i->table('oc_blog_count')
                ->where(function ($query) {
                    $query->where('language_id', 1)
                        ->where('blog_id', '>', 0);
                })
                ->orWhere(function ($query) {
                    $query->where('language_id', 2)
                        ->where('blog_id', '>', 0);
                })
                ->get();
            $count = $oc_blog_count_count->count();
            if(2 == $count){
                $conn_i->table('oc_blog_count')
                    ->where('product_id', $product_id)
                    ->where('scane', $post_scene)
                    ->update([
                        'status' => 1,
                    ]);
            }

            $conn_i->commit();

            return $this->response->json([
                'code' => 200,
                'msg' => $blog_article_id
            ]);
        } catch (\InvalidArgumentException $e) {
            $conn_i->rollBack();
            return $this->response->json([
                'code' => 400,
                'msg' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            $conn_i->rollBack();
            return $this->response->json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取商品的图片，标题，描述信息
     * @PostMapping(path="irugby_get_product")
     */
    public function irugbyGetProduct(RequestInterface $request): ResponseInterface
    {
        try {
            $conn_i = Db::connection('irugbystore');
            $getData = $request->all();
            $product_id = (int)$getData['product_id'];
            $language_id = (int)$getData['language_id'];
            $keywords = $getData['keywords'] ?? '';
            $scane = $getData['scane'] ?? '';

            if(!in_array($language_id,[1,2])){
                return $this->response->json([
                    'code' => 400,
                    'msg' => '语言错误'
                ]);
            }

            // 获取主图
            $product = $conn_i->table('oc_product')
                ->select('product_id', 'image')
                ->where('product_id', $product_id)
                ->first();
            if (!$product) {
                return $this->response->json([
                    'code' => 404,
                    'msg' => 'Product not found'
                ]);
            }

            // 获取副图
            $gallery = $conn_i->table('oc_product_image')
                ->select('image')
                ->where('product_id', $product_id)
                ->orderBy('sort_order')
                ->get()
                ->pluck('image')
                ->toArray();

            // 拼接主图+副图为字符串
            $images = array_merge([$product->image], $gallery);

            // 获取所有语言描述
            $desc_list = $conn_i->table('oc_product_description')
                ->select('language_id', 'name', 'description')
                ->where('product_id', $product_id)
                ->where('language_id', $language_id)
                ->get()
                ->toArray();

            $data = [];
            foreach ($desc_list as $desc) {
                $images_str = [];
                if(!empty($images)){
                    foreach ($images as $image) {
                        $images_str[] = 'https://irugbystore1.oss-eu-central-1.aliyuncs.com/'.$image.'?x-oss-process=image/resize,m_lfit,w_600,h_600';
                    }
                }

                $data[] = [
                    'product_id' => $product_id,
                    'keywords' => $keywords,
                    'product_image' => $images_str,
                    'product_scene' => $scane,
                    'product_url' => 'https://www.irugbystore.com/index.php?route=product/product&product_id='.$product_id,
                    'language' => ($language_id == 1) ? 'English' : 'French',
                    'language_id' => $language_id,
                    'product_name' => $desc->name,
                    'product_description' => strip_tags(html_entity_decode($desc->description))
                ];
            }

            return $this->response->json([
                '200' => $data
            ]);
        } catch (\InvalidArgumentException $e) {
            return $this->response->json([
                'code' => 400,
                'msg' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            return $this->response->json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * @PostMapping(path="irugby_lose_article_insert")
     */
    public function irugbyLoseArticleInsert(RequestInterface $request): ResponseInterface
    {
        try {
            $conn_i = Db::connection('irugbystore');
            $getData = $request->all();
            $article_id = (int)$getData['article_id'];
            $language_id = (int)$getData['language_id'];
            $add_article = false;
            if($article_id <= 0){
                return $this->response->json([
                    'code' => 400,
                    'msg' => 'article_id不存在'
                ]);
            }

            $exist = $conn_i->table('oc_blog_article_description')
                ->where('article_id', $article_id)
                ->where('language_id', $language_id)
                ->first();
            if(!$exist){
                $add_article = $conn_i->table('oc_blog_article_description')->insert([
                    'article_id' => $article_id,
                    'language_id' => $language_id,
                    'title' => trim($getData['title']),
                    'description' => trim($getData['description']),
                    'content' => trim($getData['content']),
                    'tags' => trim($getData['tags']),
                    'meta_title' => trim($getData['meta_title']),
                    'meta_description' => trim($getData['meta_description']),
                    'meta_keyword' => trim($getData['meta_keyword'])
                ]);
            }

            return $this->response->json([
                'code' => 200,
                'msg' => $add_article
            ]);

        } catch (\InvalidArgumentException $e) {
            return $this->response->json([
                'code' => 400,
                'msg' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            return $this->response->json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * @PostMapping(path="irugby_lose_article")
     */
    public function irugbyLoseArticle(RequestInterface $request): ResponseInterface
    {
        try {
            $conn_i = Db::connection('irugbystore');

            $lose_articles = $conn_i->table('oc_blog_article_description')
                ->whereIn('article_id', function ($query) {
                    $query->select('article_id')
                        ->from('oc_blog_article_description')
                        ->groupBy('article_id')
                        ->havingRaw('COUNT(DISTINCT language_id) = 1');
                })
                ->where('language_id', 2)
                ->get();

            return $this->response->json([
                'code' => 200,
                'msg' => $lose_articles
            ]);

        } catch (\InvalidArgumentException $e) {
            return $this->response->json([
                'code' => 400,
                'msg' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            return $this->response->json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * @PostMapping(path="irugby-article")
     */
    public function irugbyArticle(RequestInterface $request): ResponseInterface
    {
        try {
            $getData = $request->all();

            $product_id = (int)$getData['product_id'] ?? 0;
            $keywords = trim($getData['keywords']) ?? '';
            $scenario = trim($getData['scenario']) ?? '';
            $langs = [
                1 => "English",
                2 => "French",
            ];

            if (($product_id == 0) || (empty($keywords) || !is_string($keywords)) || (empty($scenario) || !is_string($scenario))) {
                return $this->response->json([
                    'code' => 400,
                    'msg' => '参数 product_id、keywords、scenario 必填'
                ]);
            }

            /*
             * 查到商品
             * 获取名称和描述
             */
            $conn_i = Db::connection('irugbystore');

            $pro = $conn_i->table('oc_product as p')
                ->leftJoin('oc_product_description as pd', 'p.product_id', '=', 'pd.product_id')
                ->where('p.product_id', $product_id)
                ->select([
                    'p.image',
                    'pd.name',
                    'pd.description',
                    'p.product_id',
                    $conn_i->raw('GROUP_CONCAT(DISTINCT pd.language_id ORDER BY pd.language_id) as language_ids')
                ])
                ->groupBy('p.product_id')
                ->get();

            if(!$pro){
                return $this->response->json([
                    'code' => 400,
                    'msg' => '商品不存在'
                ]);
            }

            $articleService = ApplicationContext::getContainer()->get(RugbyArticleService::class);
            $results = [];
            foreach ($pro as $product) {
                $productname = !empty($getData['productname']) ? trim($getData['productname']) : $product->name;
                $productdesc = !empty($getData['productdesc']) ? trim($getData['productdesc']) : strip_tags(html_entity_decode($product->description, ENT_QUOTES, 'UTF-8'));
                $language_ids = $product->language_ids ? explode(',', $product->language_ids) : [];

                if(!empty($language_ids)){
                    if($product->image){
                        $pathInfo = pathinfo($product->image);
                        $thumbnailPath = $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '-228x228.' . $pathInfo['extension'];
                        $fullImageUrl = 'https://www.irugbystore.com/image/cache/' . $thumbnailPath;
                    }else{
                        $fullImageUrl = "https://www.irugbystore.com/image/cache/catalog/irugbystore-logo-262x343.png";
                    }

                    $add_article_id = $conn_i->table('oc_blog_article')->insertGetId([
                        'author_id' => rand(1,3),
                        'article_list_gallery_display' => 'SLIDER',
                        'sort_order' => 1,
                        'image' => $product->image ?? 'catalog/irugbystore-logo.png',
                        'status' => 1,
                        'status_comments' => 1,
                        'date_updated' => date('Y-m-d H:i:s'),
                        'date_published' => date('Y-m-d H:i:s'),
                        'date_added' => date('Y-m-d H:i:s'),
                    ]);

                    foreach ($language_ids as $lang) {
                        //队列请求
                        $this->queue->push(new RugbyArticleJob(
                                $product_id,
                                $lang,
                                $keywords,
                                $scenario,
                                $productname,
                                $productdesc,
                                'irugbystore',
                                $add_article_id,
                                $fullImageUrl,
                                $this->loggerFactory
                            )
                        );

                        $results[] = [
                            'product_id' => $product_id,
                            'language_id' => $lang,
                            'keywords' => $keywords,
                            'scenario' => $scenario,
                            'productname' => $productname,
                            'productdesc' => $productdesc,
                            'webname' => 'irugbystore',
                            'article_id' => $add_article_id,
                            'image' => $fullImageUrl
                        ];
                    }
                }


                //直接请求
//                $results[] = $articleService->generateArticle([
//                    'name' => $productname,
//                    'desc' => $productdesc,
//                    'keywords' => $keywords,
//                    'scenario' => $scenario,
//                    'language' => $langs[$product->language_id] ?? 'English',
//                    'blogs' => [],
//                    'image' => 'dsdd.jpg',
//                ]);
            }

            return $this->response->json([
                'code' => 200,
                'msg' => $results
            ]);

        } catch (\InvalidArgumentException $e) {
            return $this->response->json([
                'code' => 400,
                'msg' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            return $this->response->json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * @PostMapping(path="irugby-review")
     */
    public function irugbyReview(RequestInterface $request): ResponseInterface
    {
        try {
            $getData = $request->all();

            $product_ids = $getData['product_ids'] ?? [];

            // 检查类型
            if (!is_array($product_ids)) {
                return $this->response->json([
                    'code' => 400,
                    'message' => 'product_ids 必须是数组',
                ]);
            }

            // 可选：如果你要限制最小数量
            if (empty($product_ids)) {
                return $this->response->json([
                    'code' => 400,
                    'message' => '请至少选择一个商品',
                ]);
            }

            /*
             * 查到商品
             * 获取名称和描述
             */
            $conn_i = Db::connection('irugbystore');

            $pro = $conn_i->table('oc_product_description')
                ->select('product_id','language_id','name','description')
                ->whereIn('product_id', $product_ids)
                ->get();

            if(!$pro){
                return $this->response->json([
                    'code' => 400,
                    'msg' => '商品不存在'
                ]);
            }

            $results = [];
            $langs = [
                1 => "English",
                2 => "French",
            ];
            foreach ($pro as $product) {
                $descriptionHtml = $product->description;
                $decodedHtml = html_entity_decode($descriptionHtml, ENT_QUOTES, 'UTF-8');
                $plainText = strip_tags($decodedHtml);

                //队列请求
                $this->queue->push(new RugbyReviewJob(
                        (int)$product->product_id,
                        (int)$product->language_id,
                        $product->name,
                        $plainText,
                        $langs[$product->language_id] ?? 'English',
                    'irugbystore'
                    )
                );

                $results[] = [
                    'product_id' => $product->product_id,
                    'product_name' => $product->name,
                    'product_description' => $plainText,
                    'language' => $langs[$product->language_id] ?? 'English',
                    'language_id' => $product->language_id,
                ];
            }

            return $this->response->json([
                'code' => 200,
                'msg' => $results,
            ]);

        } catch (\InvalidArgumentException $e) {
            return $this->response->json([
                'code' => 400,
                'msg' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            return $this->response->json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * @GetMapping(path="rugby-article")
     */
    public function rugbyArticle(RequestInterface $request): ResponseInterface
    {
        try {
            $getData = $request->all();
            $webname = trim($getData['webname'] ?? '');

            if (empty($webname) || !is_string($webname)) {
                return $this->response->json([
                    'code' => 400,
                    'msg' => '参数 webname 必填，且为字符串'
                ]);
            }

            $conn = Db::connection($webname);
            $total = 0;

            $cursor = $conn->cursor("SELECT product_id FROM oc_product WHERE status = 1 LIMIT 10");

            foreach ($cursor as $product) {
                $this->queue->push(new RugbyArticleJob((int)$product->product_id, $getData, $this->loggerFactory));
                $total++;
            }

            return $this->response->json([
                'code' => 200,
                'msg' => "已推送{$total}条任务到队列",
            ]);

        } catch (\InvalidArgumentException $e) {
            return $this->response->json([
                'code' => 400,
                'msg' => $e->getMessage()
            ]);
        } catch (\Exception $e) {
            return $this->response->json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
}

